package com.ruoyi.framework.web.service;


import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SysForgetService {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;


    /**
     * 忘记密码
     */
    public String forget(RegisterBody registerBody)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        String newPassword = password; // 默认新密码
        SysUser sysUser = userService.selectUserByUserName(username);

        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if(sysUser == null){
            msg = "用户'" + username + "'失败，账号不存在";
        }else {
            sysUser.setPassword(SecurityUtils.encryptPassword(newPassword));
            sysUser.setUpdateBy(username);
            // 4. 持久化修改到数据库
            Long[] defaultRoleIds = {2L}; // 角色数组，包含默认角色 ID
            sysUser.setDeptId(201L);
            sysUser.setRoleIds(defaultRoleIds);
            int result = userService.updateUser(sysUser);
            if (result > 0) {
                msg = "密码重置成功，新密码：" + newPassword;
            } else {
                msg = "密码重置失败，请稍后再试";
            }
        }

        return msg;
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }
}
